package com.elec.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elec.domain.ElectItem;
import com.elec.domain.ElectVo;
import com.elec.domain.R;
import com.elec.domain.entity.PaymentRecord;
import com.elec.mapper.ElectricityBillMapper;
import com.elec.domain.entity.ElectricityBill;
import com.elec.mapper.PaymentRecordMapper;
import com.elec.service.ElectricityBillService;
import com.elec.util.ThreadLocalUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 记录用户电费账单详情(ElectricityBill)表服务实现类
 *
 * @author yu
 * @since 2024-07-05 13:42:59
 */
@Service("electricityBillService")
public class ElectricityBillServiceImpl extends ServiceImpl<ElectricityBillMapper, ElectricityBill> implements ElectricityBillService {

    @Resource
    private PaymentRecordMapper paymentRecordMapper;
    @Override
    public R add(ElectricityBill electricityBill) {
        if (save(electricityBill)){
            return R.success("添加成功");
        }
        return R.error("添加失败");
    }

    @Override
    public R delete(Long id) {
        if (removeById(id)){
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }

    @Override
    public R get(Long id) {
        if (getById(id) != null){
            return R.success(getById(id));
        }
        return R.error("查询失败");
    }

    @Override
    public R getList(Integer pageNum, Integer pageSize, ElectricityBill electricityBill) {
        LambdaQueryWrapper<ElectricityBill> queryWrapper = new LambdaQueryWrapper<>();
        if (electricityBill != null){
            if (electricityBill.getBillId() != null){
                queryWrapper.eq(ElectricityBill::getBillId,electricityBill.getBillId());
            }
            if (electricityBill.getBillingPeriod() != null){
                queryWrapper.eq(ElectricityBill::getBillingPeriod,electricityBill.getBillingPeriod());
            }
            if (electricityBill.getUserId() != null){
                queryWrapper.eq(ElectricityBill::getUserId,electricityBill.getUserId());
            }
        }
        Page<ElectricityBill> page = new Page<>(pageNum,pageSize);
        page(page, queryWrapper);
        return R.success(page.getRecords(), page.getTotal());
    }

    @Override
    public R update(ElectricityBill electricityBill) {
        if (updateById(electricityBill)){
            return R.success("更新成功");
        }
        return R.error("更新失败");
    }

    @Override
    public R getElectricityConsumption() {
         //获取当前用户的所有的电费账单
        LambdaQueryWrapper<ElectricityBill> billWrapper = new LambdaQueryWrapper<>();
        Long userId = ThreadLocalUtil.getLocal();
        if (userId == null){
            userId = 1L;
        }
        billWrapper.eq(ElectricityBill::getUserId,userId);
        //向前推移一年
        Date currentDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.add(Calendar.YEAR, -1);
        Date oneYearAgo = calendar.getTime();
        billWrapper.between(ElectricityBill::getBillingPeriod, oneYearAgo, new Date());
        List<ElectricityBill> list = list(billWrapper);
        List<ElectItem> consumptionList = new ArrayList<>();
        double total = 0;
        if (list == null || list.size() == 0){
            return R.error("暂无数据");
        }
        for (ElectricityBill bill : list){
            consumptionList.add(new ElectItem(bill.getBillingPeriod(), bill.getElectricityConsumption()));
            total += bill.getElectricityConsumption();
        }
        ElectVo electVo = new ElectVo();
        electVo.setConsumptionList(consumptionList);
        electVo.setAverageConsumption(total / consumptionList.size());
        if (electVo.getConsumptionList().get(electVo.getConsumptionList().size()-1).getElectricityConsumption() > electVo.getAverageConsumption()){
            electVo.setAdvice("您的用电量超过平均值，请关注用电情况");
        } else {
            electVo.setAdvice("您的用电量低于平均值，请继续保持");
        }
        return R.success(electVo);
    }

    @Override
    public R getMyBill(Integer pageNum, Integer pageSize, ElectricityBill electricityBill) {
        Long userId = ThreadLocalUtil.getLocal();
        LambdaQueryWrapper<ElectricityBill> billWrapper = new LambdaQueryWrapper<>();
        billWrapper.eq(ElectricityBill::getUserId,userId);
        billWrapper.orderByDesc(ElectricityBill::getBillingPeriod);
        Page<ElectricityBill> page = new Page<>(pageNum, pageSize);
        page(page, billWrapper);
        return R.success(page.getRecords(), page.getTotal());
    }

    @Transactional
    @Override
    public R pay(PaymentRecord paymentRecord) {
        Long userId = ThreadLocalUtil.getLocal();
        paymentRecord.setUserId(userId.intValue());
        String uuid = IdUtil.simpleUUID();
        paymentRecord.setTransactionId(uuid);
        int insert = paymentRecordMapper.insert(paymentRecord);
        ElectricityBill bill = new ElectricityBill();
        bill.setBillId(paymentRecord.getBillId());
        bill.setPaymentStatus("paid");
        boolean b = updateById(bill);
        if (b){
            return R.success("支付成功");
        }
        return R.error("支付失败");
    }
}


